package com.maya.medicalwastes.ui;

import androidx.appcompat.app.AppCompatActivity;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.text.TextUtils;
import android.widget.TextView;
import android.widget.Toast;

import com.maya.medicalwastes.R;
import com.tbossgroup.tbscale.TBScaleAidlInterface;

import java.util.List;

public class GuideActivity extends AppCompatActivity {
    private static final String PACKAGE_NAME = "com.tbossgroup.tbscale.aidl";
    private static final String ACTION = "com.tbossgroup.tbscale.OTScaleService";

    private TBScaleAidlInterface mTBScaleAidlInterface;
    private ServiceConnection mServiceConnectionn = new ServiceConnection() {

        //绑定服务，回调onBind()方法
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mTBScaleAidlInterface = TBScaleAidlInterface.Stub.asInterface(service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mTBScaleAidlInterface = null;
        }
    };

    private static final int RESET_REFRESH_DELAY = 100;
    private static final int SERVICE_CONNECTION_DELAY = 1000;

    private static final int WAHT_REFRESH_UI = 1;
    private static final int WAHT_SERVICE_CONNECTION = 2;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == WAHT_REFRESH_UI) {
                refreshWeightRecord();
            } else if (msg.what == WAHT_SERVICE_CONNECTION) {
                try {
                    if (mTBScaleAidlInterface == null
                              || TextUtils.isEmpty(mTBScaleAidlInterface.getNetWeightString())) {
                        unbindService(mServiceConnectionn);
                        bindService();
                        return;
                    }
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        }
    };

    private TextView mTvNetWeight;
    private boolean isConfigAppInstall = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_guide);

        initView();
        bindService();
        initListener();

        if (checkPackInfo(PACKAGE_NAME)) {
            isConfigAppInstall = true;
            if (!isAppBackground(PACKAGE_NAME)) {
                Intent intent = getPackageManager().getLaunchIntentForPackage(PACKAGE_NAME);
                if (intent != null) {
                    //putExtra传递本包名，可以让sdk在开机零点获取完成后自动跳转会来
                    intent.putExtra("PackageName", this.getPackageName());
                    startActivity(intent);
                }
            }
        }
    }

       @Override
    protected void onStart() {
        super.onStart();
        if (isConfigAppInstall) {
            bindService();
            mHandler.sendEmptyMessage(WAHT_REFRESH_UI);
        } else {
            Toast.makeText(this, "智能秤配置APK未安装", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        unbindService(mServiceConnectionn);
        mHandler.removeCallbacksAndMessages(null);
    }

    private void initListener() {
//        findViewById(R.id.btnTare).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                try {
//                    mTBScaleAidlInterface.setTare();
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//        });
//        findViewById(R.id.btnZero).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                try {
//                    mTBScaleAidlInterface.setZero();
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//        });
//        findViewById(R.id.btnSettings).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (checkPackInfo(PACKAGE_NAME)) {
//                    openPackage(ScaleActivity.this, PACKAGE_NAME);
//                } else {
//                    Toast.makeText(ScaleActivity.this, "智能秤配置APK未安装", Toast.LENGTH_SHORT).show();
//                }
//            }
//        });
    }

    private void initView() {
        mTvNetWeight = findViewById(R.id.tvNetWeight);
//        mImgBattery = findViewById(R.id.img_battery);
//        mTvBatteryPer = findViewById(R.id.tv_battery_per);
    }

    private void bindService() {
        //绑定服务端的service
        Intent intent = new Intent();
        intent.setAction(ACTION);
        intent.setPackage(PACKAGE_NAME);
        //绑定的时候服务端自动创建
        bindService(intent, mServiceConnectionn, Context.BIND_AUTO_CREATE);
        mHandler.sendEmptyMessageDelayed(WAHT_SERVICE_CONNECTION, SERVICE_CONNECTION_DELAY);
    }

    private void refreshWeightRecord() {
        try {
            //获取净重
            mTvNetWeight.setText(mTBScaleAidlInterface.getNetWeight() + "");
//            //获取电量
//            EventBatteryPower batteryPower = mTBScaleAidlInterface.getBatteryPower();
//            mTvBatteryPer.setText(batteryPower.getPower() + "%");
//            mImgBattery.setPower(batteryPower.getPower());
//            if (batteryPower.isLowPower()) {
//                mTvBatteryPer.setTextColor(Color.RED);
//                mImgBattery.setColor(Color.RED);
//            } else {
//                mTvBatteryPer.setTextColor(Color.WHITE);
//                mImgBattery.setColor(Color.WHITE);
//            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        mHandler.sendEmptyMessageDelayed(WAHT_REFRESH_UI, RESET_REFRESH_DELAY);
    }

    private boolean openPackage(Context context, String packageName) {
        Context pkgContext = getPackageContext(context, packageName);
        Intent intent = getAppOpenIntentByPackageName(context, packageName);
        if (pkgContext != null && intent != null) {
            pkgContext.startActivity(intent);
            return true;
        }
        return false;
    }

    private Context getPackageContext(Context context, String packageName) {
        Context pkgContext = null;
        if (context.getPackageName().equals(packageName)) {
            pkgContext = context;
        } else {
            try {
                pkgContext = context.createPackageContext(packageName,
                        Context.CONTEXT_IGNORE_SECURITY
                                | Context.CONTEXT_INCLUDE_CODE);
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
        }
        return pkgContext;
    }

    private boolean checkPackInfo(String packname) {
        PackageInfo packageInfo = null;
        try {
            packageInfo = getPackageManager().getPackageInfo(packname, 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return packageInfo != null;
    }

    private Intent getAppOpenIntentByPackageName(Context context, String packageName) {
        String activityName = null;
        PackageManager pkgMag = context.getPackageManager();
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.setFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED | Intent.FLAG_ACTIVITY_NEW_TASK);

        List<ResolveInfo> list = pkgMag.queryIntentActivities(intent, PackageManager.GET_ACTIVITIES);
        for (int i = 0; i < list.size(); i++) {
            ResolveInfo info = list.get(i);
            if (info.activityInfo.packageName.equals(packageName)) {
                activityName = info.activityInfo.name;
                break;
            }
        }
        if (TextUtils.isEmpty(activityName)) {
            return null;
        }
        intent.setComponent(new ComponentName(packageName, activityName));
        return intent;
    }

    private boolean isAppBackground(String packageName) {
        ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
                .getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals("packageName")) {
                if (appProcess.importance != ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    return true;
                } else {
                    return false;
                }
            }
        }
        return false;
    }
}
